<?php

class attachment extends Admin {

    # 删除附件
    public function del() {
        if ( !$id = intval( G( "id" ) ) ) {
            $this->error();
            return;
        }

        $model = strtolower( G( 'model', 'hotsale' ) );
        $this->table = "attachment";
        if ( !$result = $this->find( array( "id" => $id, 'model' => $model ) ) ) {
            exit( '附件id:{$id}不存在' );
        }

        $msg = $this->delete( array( "id" => $id, 'model' => $model ) ) ? 'success' : 'failed';

        $this->table = $model;
        $this->decrField( array( 'id' => $result[ 'aid' ] ), 'attachments' );
        @unlink( WEBROOT . $result[ 'filepath' ] );
        exit( $msg );
    }

    # 批量删除附件
    public function delAll() {
        if ( !$in_id = G( 'in_id' ) ) {
            $this->error();
            return;
        }
        #删除附件
        $model = strtolower( G( 'model', 'hotsale' ) );
        $this->table = "attachment";
        exit( $this->delete( "id in ({$in_id}) and model = '{$model}' " ) ? 'success' : 'failed' );
    }

    # 上传附件
    public function up() {
        $file = upload( $this->setting[ 'updir' ] );
        if ( in_array( $file, array( 'hash', 'error' ) ) ) {
            exit( json_encode( array( 'file' => $file ) ) );
        }
        $img = @getimagesize( WEBROOT . $file ) ? 1 : 0;
        $id = $this->save( $file, $img );
        exit( json_encode( array( 'file' => $file, 'id' => $id, 'img' => $img ) ) );
    }

    # 更新默认附件
    public function upAttach() {
        if ( !$id = intval( G( "id" ) ) ) {
            $this->error();
            return;
        }
        $model = strtolower( G( 'model', 'hotsale' ) );
        $this->table = "attachment";
        $rows = array( 'isDefault' => ( G( 'v' ) ? 0 : 1 ) );
        echo $this->update( array( 'id' => $id, 'model' => $model ), $rows ) ? 'success' : 'failed';
    }

    # 保存附件
    private function save( $file, $img ) {
        $this->table = "attachment";
        $model = strtolower( G( 'model', 'hotsale' ) );
        $rows[ 'filename' ] = basename( $file );
        $rows[ 'filepath' ] = $file;
        $rows[ 'filesize' ] = formatFileSize( filesize( WEBROOT . $file ) );
        $rows[ 'dateline' ] = time();
        $rows[ 'isImage' ] = $img;
        $rows[ 'model' ] = $model;
        return $this->create( $rows );
    }
}